package com.tianji.remark.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tianji.common.autoconfigure.mq.RabbitMqHelper;
import com.tianji.common.constants.CacheConstant;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.domain.dto.LikedTimesDTO;
import com.tianji.common.utils.UserContext;
import com.tianji.remark.domain.dto.LikeRecordFormDTO;
import com.tianji.remark.domain.po.LikedRecord;
import com.tianji.remark.mapper.LikedRecordMapper;
import com.tianji.remark.service.ILikedRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.StringRedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 点赞记录表 服务实现类
 * </p>
 *
 * @author xjs
 */
@Service
public class LikedRecordServiceImpl2 extends ServiceImpl<LikedRecordMapper, LikedRecord> implements ILikedRecordService {

    @Autowired
    private RabbitMqHelper mqHelper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Set<Long> isBizLiked(List<Long> bizIds, String bizType) {
        Long userId = UserContext.getUser();
        // pipeline
        List<Object> existList = redisTemplate.executePipelined(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection connection) throws DataAccessException {
                for (Long bizId : bizIds) {
                    String key = getUserLikeRecordKey(bizId, bizType);
                    StringRedisConnection redisConnection = (StringRedisConnection) connection;
                    // 这条命令的执行结果exist回放到List<Object>来
                    Boolean exist = redisConnection.sIsMember(key, "" + userId);
                }
                return null;
            }
        });
        Set<Long> idSet = new HashSet<>();
        for (int i=0; i<existList.size();i++) {
            Object object = existList.get(i);
            Boolean exist = (Boolean)  object;
            if(exist!=null && exist){
                idSet.add(bizIds.get(i));
            }
        }
        return idSet;
//        Set<Long> idSet = new HashSet<>();
//        Long userId = UserContext.getUser();
//        for (Long bizId : bizIds) {
//            String key = getUserLikeRecordKey(bizId, bizType);
//            Boolean exist = redisTemplate.opsForSet().isMember(key, userId);
//            if(exist != null && exist){
//                idSet.add(bizId);
//            }
//        }
//        return idSet;
    }

    @Override
    public void addLikeRecord(LikeRecordFormDTO dto) {
        //获取用户id
        Long userId = UserContext.getUser();
        String userLikeRecordKey = getUserLikeRecordKey(dto.getBizId(), dto.getBizType());
        // 判断是否是个点赞
        Boolean liked = dto.getLiked();
        if(liked){
            // 说明是点赞，新增点赞记录
            Long add = redisTemplate.opsForSet().add(userLikeRecordKey, "" + userId);
            if(add != null && add > 0){
                // 添加成功， 统计点赞数量
                calcLikeTimes(dto.getBizType(), dto.getBizId());
            }
        }else{
            // 说明是取消点赞，删除点赞记录
            Long remove = redisTemplate.opsForSet().remove(userLikeRecordKey, "" + userId);
            if(remove != null && remove > 0){
                // 删除成功， 统计点赞数量
                calcLikeTimes(dto.getBizType(), dto.getBizId());
            }
        }
    }

    private void calcLikeTimes(String bizType, Long bizId){
        String userLikeRecordKey = getUserLikeRecordKey(bizId, bizType);
        Long size = redisTemplate.opsForSet().size(userLikeRecordKey);
        redisTemplate.opsForZSet().add(CacheConstant.LIKE_COUNT, bizType+":"+bizId, size);
    }

    private void sendMqMsg(Long bizId, String bizType){
        // 统计点赞数量
        Integer count = this.lambdaQuery()
                .eq(LikedRecord::getBizId, bizId)
                .eq(LikedRecord::getBizType,bizType)
                .count();
        // 发送MQ
        LikedTimesDTO likedTimesDTO = new LikedTimesDTO(bizId, count);
        String key = MqConstants.Key.LIKED_TIMES_KEY_TEMPLATE.replace("{}", bizType);
        mqHelper.send(MqConstants.Exchange.LIKE_RECORD_EXCHANGE, key, likedTimesDTO);
    }

    private String getUserLikeRecordKey (Long bizId, String bizType){
        return CacheConstant.REMARK_PREFIX + bizType+":"+bizId;
    }

}
